using AutoMapper;
using B.S.RbacData.Infrastructure;
using MediatR;
using SupplierCustomerManagement.Domain.Entities;
using B.S.RbacData.ErrorCode;
using SupplierCustomerManagement.Write.API.Applications.Commands.servicepersonals;

namespace SupplierCustomerManagement.Write.API.Applications.CommandHandlters.servicepersonals
{
    /// <summary>
    /// 新增服务人员命令处理器
    /// </summary>
    public class AddServicePersonalCommandHandler : IRequestHandler<AddServicePersonalCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<ServicePersonnel> _servicePersonalRepository;
        private readonly IMapper _mapper;
        private readonly ILogger<AddServicePersonalCommandHandler> _logger;

        public AddServicePersonalCommandHandler(
            IBaseRepository<ServicePersonnel> servicePersonalRepository,
            IMapper mapper,
            ILogger<AddServicePersonalCommandHandler> logger)
        {
            _servicePersonalRepository = servicePersonalRepository;
            _mapper = mapper;
            _logger = logger;
        }

        /// <summary>
        /// 处理新增服务人员命令
        /// </summary>
        /// <param name="request">新增服务人员命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>新增结果</returns>
        public async Task<ApiResult<int>> Handle(AddServicePersonalCommand request, CancellationToken cancellationToken)
        {
            try
            {
                _logger.LogInformation("开始新增服务人员，关联实体ID: {RelatedEntityId}, 实体类型: {RelatedEntityType}, 服务人员姓名: {Name}", 
                    request.RelatedEntityId, request.RelatedEntityType, request.Name);

                // 如果设置为默认服务人员，需要取消同一关联实体的其他默认服务人员
                if (request.IsDefault)
                {
                    var existingDefaults = _servicePersonalRepository.GetAll()
                        .Where(sp => sp.RelatedEntityId == request.RelatedEntityId 
                                   && sp.RelatedEntityType == request.RelatedEntityType 
                                   && sp.IsDefault 
                                   && !sp.IsDeleted)
                        .ToList();

                    foreach (var defaultPersonal in existingDefaults)
                    {
                        defaultPersonal.IsDefault = false;
                        defaultPersonal.UpdatedTime = DateTime.Now;
                        defaultPersonal.UpdatedBy = 1; // 后续可以从当前用户上下文获取
                        await _servicePersonalRepository.UpdateAsync(defaultPersonal);
                    }
                }

                // 映射到实体
                var servicePersonal = _mapper.Map<ServicePersonnel>(request);
                servicePersonal.CreatedTime = DateTime.Now;
                servicePersonal.CreatedBy = 1; // 后续可以从当前用户上下文获取

                // 添加到数据库
                await _servicePersonalRepository.AddAsync(servicePersonal);

                _logger.LogInformation("成功新增服务人员，服务人员ID: {ServicePersonalId}, 服务人员姓名: {Name}", 
                    servicePersonal.Id, servicePersonal.Name);

                return new ApiResult<int>
                {
                    code = ResultEnumCode.Ok,
                    message = "新增服务人员成功",
                    data = servicePersonal.Id
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "新增服务人员时发生异常，关联实体ID: {RelatedEntityId}", request.RelatedEntityId);
                
                return new ApiResult<int>
                {
                    code = ResultEnumCode.fails,
                    message = $"新增服务人员时发生异常: {ex.Message}",
                    data = 0
                };
            }
        }
    }
}